package shop.core.common.oscache;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import shop.core.util.KeyValueHelper;
import shop.services.front.area.AreaService;
import shop.services.front.area.bean.Area;
import shop.services.front.keyvalue.KeyvalueService;
import shop.services.front.keyvalue.bean.Keyvalue;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 缓存管理器。 后台项目可以通过接口程序通知该类重新加载部分或全部的缓存
 *
 * @author huangf
 */
public class FrontCache {
    private static final Logger logger = LoggerFactory.getLogger(FrontCache.class);

    @Autowired
    private KeyvalueService keyvalueService;
    @Autowired
    private AreaService areaService;

    private static SystemManager systemManager;

    @Autowired
    public void setSystemManager(SystemManager systemManager) {
        FrontCache.systemManager = systemManager;
    }


    /**
     * 加载key-value键值对
     */
    public void loadKeyValue() {
        logger.info("load...");
        KeyValueHelper.load(keyvalueService.selectList(new Keyvalue()));
    }

    /**
     * 加载省市区数据
     */
    public void loadArea() {
        logger.error("loadArea...");
        Area area = new Area();
        List<Area> areas = areaService.selectList(area);
        List<Area> rootAreas = Lists.newArrayList();
        for (Area a : areas) {
            if ("0".equals(a.getPcode())) {
                rootAreas.add(a);
            }
        }
        if (rootAreas.size() == 0) {
            return;
        }

        for (Area a : rootAreas) {
            getAreaByDigui(a, areas);
        }

        Map<String, Area> map = new TreeMap<String, Area>();
        for (Area a : rootAreas) {
            map.put(a.getCode(), a);
        }
        systemManager.setAreaMap(map);
    }


    /**
     * 递归加载省份下的：城市、区域、以后还会有街道的数据
     *
     * @param item
     * @param areas 所有的地区列表
     */
    private void getAreaByDigui(Area item, final List<Area> areas) {
        List<Area> children = Lists.newArrayList();
        for (Area a : areas) {
            if (item.getCode().equals(a.getPcode())) {
                children.add(a);
            }
        }

        item.setChildren(children);
        if (children.size() == 0) {
            return;
        }

        for (Area a : children) {
            getAreaByDigui(a, areas);
        }
    }


    /**
     * 加载全部的缓存数据
     *
     * @throws Exception
     */
    public void loadAllCache() throws Exception {
        logger.info("loadAllCache...");
        loadKeyValue();
        loadArea();
        logger.info("前台缓存加载完毕!");
    }
}
